package reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 使用指定的构造器实例化对象
 */
public class ReflectDemo3 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Person p1 = new Person();
        System.out.println(p1);//Person{name='张三', age=22}
        Person p = new Person("李四",22);
        System.out.println(p);//Person{name='李四', age=22}

        //1.获取类对象
        Class cls = Class.forName("reflect.Person");
        /*
            2.java.lang.reflect.Constructor
            Constructor的每一个实例用于表示一个构造器,使用他可以相当于调用该构造器实例化对象
         */
        Constructor c = cls.getConstructor();//获取默认无参构造器
        Object obj1 = c.newInstance();//不需要参入实参
        System.out.println(obj1);//Person{name='张三', age=22}

        //Person(String,int)
        Constructor d = cls.getConstructor(String.class,int.class);
        Object obj = d.newInstance("王五",33);
        System.out.println(obj);//Person{name='王五', age=33}




    }
}
